package com.gee.spring.cloud.data.transform.core.center.config.handler;

import com.gee.spring.cloud.common.core.entity.center.config.TransformDsl;
import com.gee.spring.cloud.common.starter.config.event.CenterConfigEventHandler;
import com.gee.spring.cloud.common.starter.feign.center.config.TransformDslClient;
import com.gee.spring.cloud.data.transform.core.dispatch.BaseDataDispatcher;
import com.gee.spring.cloud.data.transform.core.dispatch.SocketManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gepengjun
 * @since 2024/3/19 14:38
 */
@Component
public class TransformDslHandler extends CenterConfigEventHandler<TransformDsl> {

    public final ConcurrentHashMap<Long, TransformDsl> TRANSFORM_DSL_MAP = new ConcurrentHashMap<>();


    @Autowired
    private TransformDslClient transformDslClient;

    @Autowired
    private BaseDataDispatcher baseDataDispatcher;

    @Autowired
    private SocketManager socketManager;

    public TransformDsl getById(Long id){
        return TRANSFORM_DSL_MAP.computeIfAbsent(id, tId -> transformDslClient.getById(tId).getData());
    }

    @Override
    public void handlerUpdate(List<TransformDsl> dataList, List<TransformDsl> oldList) {
        for (int i = 0; i < dataList.size(); i++) {
            TransformDsl newTransformDsl = dataList.get(i);
            TransformDsl oldTransformDsl = oldList.get(i);
            TRANSFORM_DSL_MAP.computeIfPresent(newTransformDsl.getId(), (id, old) -> newTransformDsl);
            baseDataDispatcher.updateTransformDsl(newTransformDsl, oldTransformDsl);
            socketManager.updateTransformDsl(newTransformDsl, oldTransformDsl);
        }
    }

    @Override
    public void handlerDelete(List<TransformDsl> oldList) {
        oldList.forEach(transformDsl -> TRANSFORM_DSL_MAP.remove(transformDsl.getId()));
    }
}
